package pe.gastobien.app.layer.controller;

import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import pe.gastobien.app.domain.User;
import pe.gastobien.app.layer.service.CategoryService;
import pe.gastobien.app.layer.service.UserService;

@WebServlet({"/login","/logout"})
public class UserController extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String url = "";
		String alias = request.getServletPath();
		if(alias.equals("/login"))
		{
			UserService service = new UserService();
			String login = request.getParameter("login");
			String password = request.getParameter("password");
			try
			{
				Boolean isAuthenticated = service.Authenticate(login, password);
				if(isAuthenticated)
				{
					HttpSession session = request.getSession(true);
					CategoryService categoryService = new CategoryService();
					User user = service.getUserByLogin(login);					
					List<pe.gastobien.app.domain.Category> categories = categoryService.getCategories(user.getUserID(),2013,8);
					session.setAttribute("login", user.getLogin());
					session.setAttribute("categories", categories);
					session.setAttribute("user", user);
					url = "home.jsp";				
				}
				else
				{
					request.setAttribute("error", "usuario invalido");
					url = "login.jsp";
				}
				
				
			}catch (Exception e) {
				request.setAttribute("error", e.getMessage());
				url = "login.jsp";
			}
			
			response.sendRedirect(url);
		}
	}
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String alias = request.getServletPath();
		if(alias.equals("/logout")){
			logout(request,response);
		}
	}
	
	private void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		session.invalidate();
		RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
		rd.forward(request, response);
	}

}
